import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/counter'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/chat',
    },
    {
      path: '/',
      name: 'home',
      component: () => import('../views/home/IndexView.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '/chat',
          name: 'chat',
          component: () => import('../views/chat/IndexView.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: '/friend',
          name: 'friend',
          component: () => import('../views/friend/IndexView.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: '/space',
          name: 'space',
          component: () => import('../views/space/IndexView.vue'),
          meta: { requiresAuth: true },
        },
      ],
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login/IndexView.vue'),
      meta: { requiresAuth: false },
    },
  ],
})

// 路由守卫
router.beforeEach((to, _from, next) => {
  const userStore = useUserStore()

  // 初始化用户信息（从localStorage恢复）
  if (!userStore.currentUser) {
    userStore.initUser()
  }

  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth)
  const isLoggedIn = userStore.isLoggedIn

  if (requiresAuth && !isLoggedIn) {
    // 需要登录但未登录，跳转到登录页
    next('/login')
  } else if (to.path === '/login' && isLoggedIn) {
    // 已登录但访问登录页，跳转到聊天页
    next('/chat')
  } else {
    next()
  }
})

export default router
